<?php

class Engine_Core_Collection extends Engine_Core_Collection_Iterator
{
	protected $_page;
	protected $_perPage;
	protected $_countAll;
	protected $itemEntityPrefix = null;

	/**
	 * @var Adapter
	 */
	protected $_adapter;

    public function __construct()
    {
    }

    public function itemAppend($key, $item)
    {
        $this->items[$key] = $item;
    }

    public function items($index = null)
    {
        if ($index == null)
        {
            return $this->items;
        }
        elseif (array_key_exists($index, $this->items))
        {
            return $this->items[$index];
        }
    }

	public function getItemById($id)
	{
		foreach($this->items as $item) {
			if ($item->id == $id)
			{
				return $item;
			}
		}
	}

    public function keys()
    {
        return array_keys($this->items);
    }

	/**
	 * @param string $var
	 * @param bool $filtered
	 * @param bool $unique
	 * @return array
	 */
	public function getCol($var, $filtered = false, $unique = false)
	{
		$result = array();

		foreach($this->items as $item)
		{
			$result[] = $item->{$var};
		}

		$result = $filtered ? array_filter($result) : $result;
		$result = $unique   ? array_unique($result) : $result;

		return $result;
	}

    public function toArray()
    {
        $a = array();
        foreach ($this AS $key => $item)
        {
            $a[$key] = $item->toArray();
        }
        return $a;
    }

    public function count()
    {
        return (int) count($this->items);
    }

    public function clear()
    {
        $this->items = array();
    }

	public function itemDelete($key, $item)
	{
		unset($this->items[$key]);
	}

	public function setPage($value)
	{
		$this->_page = $value;

		return $this->getPage();
	}

	public function setPerPage($value)
	{
		$this->_perPage = $value;

		return $this->getPerPage();
	}

	public function setCountAll($value)
	{
		$this->_countAll = $value;

		return $this->getCountAll();
	}

	public function getPage()
	{
		return $this->_page;
	}

	public function getPerPage()
	{
		return $this->_perPage;
	}

	public function getPageCount()
	{
		return (int) ceil($this->getCountAll() / $this->getPerPage());
	}

	public function isFirstPage()
	{
		return 1 == $this->getPage();
	}

	public function isLastPage()
	{
		return $this->getPageCount() <= $this->getPage();
	}

	public function getCountAll()
	{
		return (int) $this->_countAll;
	}

	public function itemEntityPrefix()
	{
		return $this->itemEntityPrefix;
	}

	public function tags()
	{
		return $this->keysWithPrefix();
	}

	public function keysWithPrefix()
	{
		$result = array();
		foreach ($this->keys() AS $key)
		{
			$result[] = $this->itemEntityPrefix() . $key;
		}
		return $result;
	}
}